package com.lys.emsystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lys.emsystem.entity.Admin;
import com.lys.emsystem.mapper.AdminMapper;
import com.lys.emsystem.service.IAdminService;
import com.lys.emsystem.service.SchoolService;
import com.lys.emsystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liyansheng
 * @since 2022-05-02
 */
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private IAdminService iAdminService;
    @GetMapping("/analyze")
    public Result getAnalysisData(HttpSession session) {
        return iAdminService.getAnalyzeData(session);
    }

    @PostMapping
    public Result getAdmins(@RequestBody Admin admin) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        if (admin.getName() != null) {
            wrapper.eq("name", admin.getName());
        }
        Page<Admin> page = adminMapper.selectPage(new Page<>(admin.getPageIndex(), admin.getPageSize()), wrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalCount", page.getTotal());
        map.put("list", page.getRecords());
        return Result.buildResult(Result.Status.OK, map);
    }
    @PostMapping("/add")
    public Result addAdmin(@RequestBody Admin admin) {
    //    密码加密
        if (admin.getPassword() != null) {
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        }else {
        //    设置默认密码（账号后6位）
            admin.setPassword(DigestUtils.md5DigestAsHex(admin.getAccount().substring(4).getBytes()));
        }
        if (adminService.save(admin)) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.ERROR);
        }
    }

    @PostMapping("/update")
    public Result updateAdmin(@RequestBody Admin admin) {
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        if (adminService.updateById(admin)) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.ERROR);
        }
    }

    @PostMapping("/delete/{id}")
    public Result deleteAdmin(@PathVariable("id") Integer id) {
        if (adminService.removeById(id)) {
            return Result.buildResult(Result.Status.OK);
        } else {
            return Result.buildResult(Result.Status.ERROR);
        }
    }

}
